<template>
  <section class="component modify-config">
    <el-tabs v-model="currentTab">
      <el-tab-pane label="规则基本信息" name="config-base">
        <config-base :disabledData="disabledData" :show="show" :val="val.strategyStatus" ref="config-base" v-model="configBaseModel"></config-base>
      </el-tab-pane>
      <el-tab-pane label="设置分案策略" name="distribute-rule">
        <distribute-rule :disabledData="disabledData" ref="distribute-rule" v-model="distributeModel" :casePoolTypes="configBaseModel.casePoolTypes"></distribute-rule>
      </el-tab-pane>
    </el-tabs>
    <div class="operate-buttons">
      <el-button @click="emitClose">关闭</el-button>
      <el-button @click="submit" v-if="(!disabledData&&show)||val.strategyStatus==='READY'">保存</el-button>
      <el-button @click="terminationClick(1)" v-if="val.strategyStatus==='READY'&&!show">作废</el-button>
      <el-button @click="terminationClick(2)" v-if="val.strategyStatus==='PUBLISHED'&&!show">终止</el-button>
    </div>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Dependencies } from "~/core/decorator";
import { Prop, Emit, Watch } from "vue-property-decorator";
import ConfigBase from "./config-base.vue";
import DistributeRule from "./distribute-rule.vue";
import DistributionPattern from "~/components/distribution-common/distribution-pattern.vue";
import { StrategyConfigService } from "~/services/dataimp-service/strategy-config.service";
import { FilterService } from "~/utils/filter.service";
import { State } from "vuex-class";

@Component({
  components: {
    ConfigBase,
    DistributeRule,
    DistributionPattern
  }
})
export default class ModifyConfig extends Vue {
  @Dependencies(StrategyConfigService)
  private strategyConfigService: StrategyConfigService;
  @State private outSourceList;

  @Prop({ required: true })
  private strategyId: any;
  @Prop({ type: Boolean })
  private disabledData: boolean;
  @Prop({ type: Boolean })
  private show: boolean;

  private currentTab = "config-base";

  private id = "";
  private distributeMode = "";
  private distributeModel: any = {};
  private configBaseModel: any = {};
  private val: any = {};

  @Emit("close")
  private emitClose() {
    this.currentTab = "config-base";
    this.initData();
  }

  @Emit("success")
  private emitSuccess() {
    this.$message.success("操作成功");
    this.emitClose();
  }

  private refresh() {
    if (this.strategyId) {
      this.strategyConfigService
        .getOneById(this.strategyId)
        .subscribe(this.revertDataNext);
    } else {
      this.initData();
    }
  }

  private submit() {
    if ((this.distributeModel.assignModel === 'COLLECTOR' || (this.configBaseModel.casePoolTypes && (this.configBaseModel.casePoolTypes[0]==='WAIT_DISTRIBUTION' || this.configBaseModel.casePoolTypes[0]==='RECOVERED_DISTRIBUTION'))) && this.distributeModel.collectionDays > this.distributeModel.limitDays) {
      this.$message.error("催收天数不能大于" + this.distributeModel.limitDays);
      return;
    }
    if (this.distributeModel.assignModel !== 'COLLECTOR' && this.configBaseModel.casePoolTypes && this.configBaseModel.casePoolTypes[0]!=='WAIT_DISTRIBUTION' && this.configBaseModel.casePoolTypes[0]!=='RECOVERED_DISTRIBUTION') {
      this.distributeModel.collectionDays = ''
      this.distributeModel.limitDays = ''
    }
    const panels = ["config-base", "distribute-rule"];
    const validates = panels.map(v => {
      const component = this.$refs[v] as any;
      return component.validate().catch(e => Promise.reject(e));
    });
    Promise.all(validates)
      .then(x => {
        const result = {
          ...this.distributeModel,
          ...this.configBaseModel,
          id: this.id
        };
        if (this.id) {
          this.strategyConfigService
            .updateStrategy(result)
            .subscribe(this.emitSuccess);
        } else {
          this.strategyConfigService
            .createStrategy(result)
            .subscribe(this.emitSuccess);
        }
      })
      .catch(v => (this.currentTab = v));
  }
  /**
   * 作废/终止
   */
  private terminationClick(val) {
    const terminationModel: any = {
      id: this.id,
      strategyStatus: val === 1 ? "ABOLISHED" : "TERMINATED"
    };
    this.strategyConfigService
      .updateStrategyStatus(terminationModel)
      .subscribe(data => {
        this.$message.success("操作成功！");
        this.emitClose();
        this.initData();
        this.emitSuccess();
      });
  }

  private initData() {
    this.id = "";
    this.distributeModel = {
      assignModel: "",
      departmentId: "",
      departmentIds: [],
      strategyCaseType: "",
      users: [],
      distributeType: "",
      outEndCycle: "",
      distributeMode: "",
      collectionDays: '',
      limitDays: ''
    };
    this.configBaseModel = {
      strategyStatus: "READY",
      commonState: "",
      formulaJson: "[]",
      name: "",
      strategyType: "",
      priority: 5,
      casePoolTypes: []
    };
    this.distributeMode = "";
    const configBaseTab: any = this.$refs["config-base"];
    if (configBaseTab) configBaseTab.reset();
    const distributeRuleTab: any = this.$refs["distribute-rule"];
    if (distributeRuleTab) distributeRuleTab.reset();
  }

  /**
   * 回显数据下一步
   */
  private revertDataNext(val) {
    const outData: any = [];
    if (val.outsourceIds) {
      this.outSourceList.map(v => {
        if (val.outsourceIds.find(m => m === v.id)) {
          outData.push({
            outsourceId: v.id,
            outsName: v.outsName
          });
        }
      });
    }
    this.val = val;
    this.id = val.id;
    this.distributeModel = {
      assignModel: val.assignModel,
      departmentId: val.departmentId,
      strategyCaseType: val.strategyCaseType,
      users: val.users,
      distributeType: val.distributeType,
      distributeMode: val.distributeMode,
      outEndCycle: val.outEndCycle,
      entrustData: outData,
      collectionDays: val.collectionDays
    };
    this.configBaseModel = {
      casePoolTypes: val.casePoolTypes,
      strategyStatus: val.strategyStatus,
      executionFrequency: val.executionFrequency,
      startDate: FilterService.dateTimeFormat(val.startDate),
      endDate: FilterService.dateTimeFormat(val.endDate),
      commonState: val.commonState,
      formulaJson: val.formulaJson,
      name: val.name,
      strategyType: val.strategyType,
      priority: val.priority,
      timeType: val.timeType,
      intervals: val.intervals
    };
    this.distributeMode = val.distributeMode;
  }

  private created() {
    this.initData();
  }
}
</script>

<style lang="less" scoped>
</style>
